# coding:utf-8
import sys
from pathlib import Path
from PyQt5.QtCore import Qt, QThread, pyqtSignal
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QFrame, QHBoxLayout, QWidget
from qfluentwidgets import (NavigationItemPosition, MessageBox, setTheme, Theme, FluentWindow, StateToolTip,
                            NavigationAvatarWidget, qrouter, SubtitleLabel, setFont, InfoBadge,
                            InfoBadgePosition)
from qfluentwidgets import FluentIcon as FIF
from Ui_info import Ui_info_form
from Ui_view import Ui_PhotoView
from Ui_run import Ui_RunForm
from Ui_result import Ui_ResultForm
from Ui_report import Ui_ReportForm
from cal import Calculator, Predictor

class Widget(QFrame):

    def __init__(self, text: str, parent=None):
        super().__init__(parent=parent)

        self.label = SubtitleLabel(text, self)
        self.hBoxLayout = QHBoxLayout(self)

        setFont(self.label, 24)
        self.label.setAlignment(Qt.AlignCenter)
        self.hBoxLayout.addWidget(self.label, 1, Qt.AlignCenter)
        self.setObjectName(text.replace(' ', '-'))


class Window(FluentWindow):

    def __init__(self):
        super().__init__()
        self.initWindow()
        # 检测信息界面
        self.info_form = Ui_info_form()
        self.infoInterface = QFrame()
        self.infoInterface.setObjectName('info')
        self.info_form.setupUi(self.infoInterface, parent=self.infoInterface)
        
        # 图像选择和预览界面
        self.view_form = Ui_PhotoView()
        self.viewInterface = QFrame()
        self.viewInterface.setObjectName('view')
        self.view_form.setupUi(self.viewInterface)
        
        # 智能处理界面
        self.run_form = Ui_RunForm()
        self.runInterface = QFrame()
        self.runInterface.setObjectName('run')
        self.run_form.setupUi(self.runInterface)
        
        # 结果展示界面  
        self.result_form = Ui_ResultForm()
        self.resultInterface = QFrame()
        self.resultInterface.setObjectName('result')
        self.result_form.setupUi(self.resultInterface, parents=self.resultInterface)

        # 报告界面  
        self.report_form = Ui_ReportForm()
        self.reportInterface = QFrame()
        self.reportInterface.setObjectName('report')
        self.report_form.setupUi(self.reportInterface)

        # 设置界面
        self.settingInterface = Widget('Setting Interface', self)

        self.initNavigation()
        self.initWindow()

        self.file_path = None

        # 界面跳转
        self.info_form.next_pb.clicked.connect(lambda:self.switchTo(self.viewInterface))
        self.view_form.PreviousPushButton.clicked.connect(lambda:self.switchTo(self.infoInterface))
        self.view_form.NextPushButton.clicked.connect(self.view_next)
        self.run_form.PreviousPushButton.clicked.connect(lambda:self.switchTo(self.viewInterface))
        self.run_form.NextPushButton.clicked.connect(self.run_next)
        self.result_form.PreviousPushButton.clicked.connect(lambda:self.switchTo(self.runInterface))
        self.result_form.NextPushButton.clicked.connect(self.result_next)
        self.report_form.PreviousPushButton.clicked.connect(lambda:self.switchTo(self.resultInterface))     

    def view_next(self):
        self.switchTo(self.runInterface)
        if self.view_form.file_path is not None:
            self.file_path = self.view_form.file_path
            print(f'view_next: {self.file_path}')
            self.run_form.file_path = self.file_path
            self.result_form.file_path = self.file_path
            self.report_form.file_path = self.file_path
    
    def run_next(self):
        self.switchTo(self.resultInterface)
        if self.run_form.file_path is not None:
            print(f'run_next:{self.result_form.file_path}')
            p = Path(self.file_path)
            floder_name_list = [str(path).split('\\')[-1] for path in p.iterdir() if path.is_dir()]
            self.result_form.FileSelectComboBox .clear()
            self.result_form.FileSelectComboBox.addItems(floder_name_list)

    def result_next(self):
        self.switchTo(self.reportInterface)
        #self.report_form.stateToolTip = StateToolTip('正在训练模型', '请耐心等待哦~~', parent=self.reportInterface)
        #self.report_form.stateToolTip.move(610, 40)
        #self.report_form.stateToolTip.show()
        #print(f'result_next:{self.report_form.file_path}')
        cal = Calculator(file_path=self.file_path)
        # 加入多进程
        cal.calculate()
        self.data_heng = cal.data_heng
        self.data_zong = cal.data_zong

        self.report_form.A3BodyLabel.setText(str(cal.A3_zong))
        self.report_form.A5BodyLabel.setText(str(cal.A5_zong))
        self.report_form.F10BodyLabel.setText(str(cal.f10_zong))
        self.report_form.F20BodyLabel.setText(str(cal.f20_zong))
        self.report_form.F15BodyLabel.setText(str(cal.f15_zong))

        self.report_form.A3BodyLabel_2.setText(str(cal.A3_heng))
        self.report_form.A5BodyLabel_2.setText(str(cal.A5_heng))
        self.report_form.F10BodyLabel_2.setText(str(cal.f10_heng))
        self.report_form.F20BodyLabel_2.setText(str(cal.f20_heng))
        self.report_form.F15BodyLabel_2.setText(str(cal.f15_heng))

        self.report_form.plot_heng = self.report_form.canvas_heng.figure.subplots()
        self.report_form.plot_heng.hist(self.data_heng, bins=10, color='blue', alpha=0.5)
        

        self.report_form.plot_zong = self.report_form.canvas_zong.figure.subplots()
        self.report_form.plot_zong.hist(self.data_zong, bins=10, color='red', alpha=0.5)
        self.report_form.plot_zong.figure.canvas.draw()
        self.report_form.plot_heng.figure.canvas.draw()

        #self.report_form.stateToolTip.setContent('计算完成了 😆')
        #self.report_form.stateToolTip.setState(True)
        #self.report_form.stateToolTip = None



    def progress_ring(self):
        p = Predictor(file_path=self.file_path)
        self.run_form.ProgressRing.setValue(0)
        self.run_form.RunPushButton.setEnabled(False)
        for i in p.predict():
            self.run_form.ProgressRing.setValue(i)

        self.run_form.ProgressRing.setValue(100)
        self.run_form.RunPushButton.setEnabled(True)

    def initNavigation(self):
        self.addSubInterface(self.infoInterface, FIF.TILES, '检测信息')
        self.addSubInterface(self.viewInterface, FIF.CAMERA, '图像预览')
        self.addSubInterface(self.runInterface, FIF.ROBOT, '智能处理')
        self.addSubInterface(self.resultInterface, FIF.VIEW, '分割效果')
        self.addSubInterface(self.reportInterface, FIF.DOCUMENT, '报告')
        self.navigationInterface.addSeparator()

        # add custom widget to bottom
        self.navigationInterface.addWidget(
            routeKey='avatar',
            widget=NavigationAvatarWidget('邱水', 'resource/shoko.png'),
            position=NavigationItemPosition.BOTTOM,
        )
        self.addSubInterface(self.settingInterface, FIF.SETTING, 'Settings', NavigationItemPosition.BOTTOM)

    def initWindow(self):
        self.resize(980, 800)
        self.setWindowIcon(QIcon(':/qfluentwidgets/images/logo.png'))
        self.setWindowTitle('微观均匀性检测 V1.0')

        desktop = QApplication.desktop().availableGeometry()
        w, h = desktop.width(), desktop.height()
        self.move(w//2 - self.width()//2, h//2 - self.height()//2)

if __name__ == '__main__':
    QApplication.setHighDpiScaleFactorRoundingPolicy(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps)
    app = QApplication(sys.argv)
    w = Window()
    w.show()
    
    class ProgressThread(QThread): 
        def __init__(self, parent=None):  # 定义初始化方法，接受一个父级对象参数
            super(ProgressThread, self).__init__(parent)  # 调用父类的初始化方法
            finished = pyqtSignal()  # 创建一个pyqtSignal信号，用于在线程运行结束时发射信号
    
        def run(self):  # 定义运行方法
            w.progress_ring()  # 调用aw对象的progress_bar方法，在线程中执行相应的操作
            self.finished.emit()  # 发射finished信号，通知线程执行结束

    thread = ProgressThread() 
    w.run_form.RunPushButton.clicked.connect(thread.start)  # 绑定按钮的点击信号到线程的start方法，启动线程
    sys.exit(app.exec())